#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <syslog.h>
#include <errno.h>

#include <proto.h>

#include "conf.h"

static pthread_t tid_chn[CHNMAX];

static void *thr_channel(void *p)
{
	struct chn_entry_st *chnp=p;
	struct msg_st *s_msgp;
	int tok, len;

	while (1) {
		len = medialib_read_chn(chnp->chnid, s_msgp->un.data.byte, DATAMAX);
		if (len<0) {
			syslog(LOG_ERR, "%s/%s: medialib_read_chn() failed.", __FILE__, __FUNCTION__);
			exit(1);
		}
		len += sizeof(struct msg_st);
		sendto(configure.send_sd, s_msgp, len, 0, (void*)&configure.dst_addr, sizeof(configure.dst_addr));
	}
}

int thr_channel_create(struct chn_entry_st *p)
{
	int err;
	struct chn_entry_st *chnp=p;

	err=pthread_create(tid_chn+chnp->chnid, NULL, thr_channel, p);
	if (err) {
		syslog(LOG_ERR, "%s/%s/%d: Channel %d create failed!", __FILE__, __FUNCTION__, __LINE__, p->chnid);
		exit(1);
	}
	syslog(LOG_DEBUG, "%s/%s/%d: Channel %d created", __FILE__, __FUNCTION__, __LINE__, p->chnid);

	return 0;
}

int thr_channel_destroy(chnid_t id)
{
	if (id<0 || id>CHNMAX) {
		return EINVAL;
	}
	pthread_cancel(tid_chn[id]);
	pthread_join(tid_chn[id], NULL);
	syslog(LOG_DEBUG, "%s/%s/%d: Channel %d terminated", __FILE__, __FUNCTION__, __LINE__, id);

	return 0;
}

int thr_channel_destroyall(void)
{
	syslog(LOG_WARNING, "%s/%s is not completed yet.", __FILE__, __FUNCTION__);
	return 0;
}

